package smecta.client.print.util;

import lombok.Data;
import org.springframework.util.ObjectUtils;
import smecta.client.print.common.exceptions.ServiceException;

import javax.annotation.PostConstruct;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

@Data
public class AuthUtil {

    static String filePath = "./dependencies/ini/auth.ini";

    private static final String ATTR_PK = "privateKey";

    private static final String ATTR_AC = "authCode";

    private static Properties properties;

    public static void loadPrintSettings() {
        properties = new Properties();
        try (FileInputStream input = new FileInputStream(filePath)) {
            properties.load(input);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    public static boolean check() {
        if (!ObjectUtils.isEmpty(properties)) {
            if (!ObjectUtils.isEmpty(properties.getProperty(ATTR_PK)) && !ObjectUtils.isEmpty(properties.getProperty(ATTR_AC))) {
                String machineCode = DecodeUtil.decrypt(properties.getProperty(ATTR_AC).toString(), DecodeUtil.generatePrivateKey(properties.get(ATTR_PK).toString()));
                if (MachineCodeUtil.generateMachineCode().equals(machineCode)) {
                    return true;
                }
            }
        }
        return false;
    }

    public static void saveAuthCode(String authCode) {
        properties.put(ATTR_AC, authCode);
        saveProperties();
    }

    // 可以添加一个通用的保存方法
    public static void saveProperties() {
        try (FileOutputStream output = new FileOutputStream(filePath)) {
            properties.store(output, "Configuration updated");
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }
}
